// 详细的API测试脚本
const axios = require('axios');

const BASE_URL = 'http://localhost:3000';

async function testWithDetails(name, url, method = 'GET', data = null) {
  try {
    console.log(`🔍 测试 ${name}...`);
    console.log(`   URL: ${method} ${url}`);
    
    const config = {
      method: method.toLowerCase(),
      url: url,
      timeout: 5000,
    };
    
    if (data) {
      config.data = data;
      config.headers = {
        'Content-Type': 'application/json'
      };
      console.log(`   数据:`, JSON.stringify(data));
    }
    
    const response = await axios(config);
    console.log(`✅ ${name} 成功!`);
    console.log(`   状态码: ${response.status}`);
    console.log(`   响应:`, JSON.stringify(response.data, null, 2));
    return true;
  } catch (error) {
    console.error(`❌ ${name} 失败!`);
    
    if (error.code) {
      console.error(`   错误代码: ${error.code}`);
    }
    
    if (error.response) {
      console.error(`   HTTP状态码: ${error.response.status}`);
      console.error(`   响应数据:`, error.response.data);
    } else if (error.request) {
      console.error(`   请求错误: 无法连接到服务器`);
      console.error(`   详情: ${error.message}`);
    } else {
      console.error(`   错误: ${error.message}`);
    }
    return false;
  }
}

async function checkServerStatus() {
  console.log('🔍 检查服务器状态...');
  
  try {
    const response = await axios.get(`${BASE_URL}/health`, { timeout: 2000 });
    console.log('✅ 服务器正在运行!');
    return true;
  } catch (error) {
    if (error.code === 'ECONNREFUSED') {
      console.log('❌ 服务器未启动或端口3000被占用');
      console.log('💡 请确保运行了服务器: node simple-server.js');
    } else {
      console.log('❌ 服务器连接失败:', error.message);
    }
    return false;
  }
}

async function runDetailedTests() {
  console.log('🚀 开始详细API测试...\n');
  
  // 首先检查服务器状态
  const serverRunning = await checkServerStatus();
  console.log('');
  
  if (!serverRunning) {
    console.log('⚠️  服务器未运行，跳过API测试');
    return;
  }
  
  // 测试各个接口
  await testWithDetails('健康检查', `${BASE_URL}/health`);
  console.log('');
  
  await testWithDetails('DeepSeek状态', `${BASE_URL}/api/deepseek/status`);
  console.log('');
  
  await testWithDetails('DeepSeek聊天', `${BASE_URL}/api/deepseek/chat`, 'POST', {
    content: '你好，请简单介绍一下你自己'
  });
  console.log('');
  
  console.log('✨ 详细测试完成！');
}

// 立即执行
runDetailedTests(); 